package masterjava.common.client.gxt.base.combo;

import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import masterjava.common.client.gxt.base.model.GenericListener;
import masterjava.common.client.gxt.base.model.GenericModel;
import masterjava.common.shared.HasKey;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;

/**
 * User: gkislin
 * Date: 8/2/11
 */
public class GenericComboBox<T extends HasKey> extends ComboBox<GenericModel<T>> {
    private final Iterator<T> itemIterator;

    public GenericComboBox(T tabItem) {
        this(Collections.singletonList(tabItem));
    }

    public GenericComboBox(T[] tabItems) {
        this(Arrays.asList(tabItems));
    }

    public GenericComboBox(Iterable<T> tabIterable) {
        this.itemIterator = tabIterable.iterator();
        setTriggerAction(ComboBox.TriggerAction.ALL);
        setEditable(false);
        setDisplayField(GenericModel.KEY);
        setStore(new ListStore<GenericModel<T>>());

        boolean first = true;
        while (itemIterator.hasNext()) {
            GenericModel<T> model = new GenericModel<T>(itemIterator.next());
            store.add(model);
            if (first) {
                setValue(model);
                first = false;
            }
        }
    }

    public void addListener(final GenericListener<T> listener) {
        addSelectionChangedListener(new SelectionChangedListener<GenericModel<T>>() {
            @Override
            public void selectionChanged(SelectionChangedEvent<GenericModel<T>> se) {
                listener.onEvent(se.getSelectedItem().getData());
            }
        });
    }
}
